<?php

namespace Cube\Bundle\CoreBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class InjectManagerCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasParameter('cube.entity_classes')) {
            return;
        }
        $entityClasses = $container->getParameter('cube.entity_classes');
        $managers = $container->findTaggedServiceIds('cube.manager');

        foreach ($managers as $id => $tags) {
            foreach ($tags as $tag) {
                if (!isset($tag['entityClass']) || !isset($entityClasses[$tag['entityClass']])) {
                    throw new \LogicException(sprintf('Missing "entityClass" attribute for service "%s"', $id));
                }
                $container->findDefinition($id)
                    ->addMethodCall('setEntityClass', $entityClasses[$tag['entityClass']]);
            }
        }
    }
}